package com.lzx.applib.okhttp;

import com.lzx.applib.utils.LogUtil;

import java.io.IOException;
import java.util.Map;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Lzx on 16/11/09 0009.
 */
public class BaseInterceptor implements Interceptor {

    private static final String TAG = "BaseInterceptor";

    private final Map<String, String> parameters;
    private final Map<String, String> headers;

    public BaseInterceptor(Map<String, String> headers, Map<String, String> parameters) {
        this.headers = headers;
        this.parameters = parameters;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request original = chain.request();

        HttpUrl originalUrl = original.url();
        HttpUrl.Builder urlBuilder = originalUrl.newBuilder();
        if (parameters != null) {
            for (String key : parameters.keySet()) {
                urlBuilder.addQueryParameter(key, parameters.get(key));
            }
        }
        HttpUrl newUrl = urlBuilder.build();

        Request.Builder requestBuilder = original.newBuilder();
        if (headers != null) {
            for (String key : headers.keySet()) {
                requestBuilder.header(key, headers.get(key));
            }
        }
        Request newRequest = requestBuilder.url(newUrl).build();
        LogUtil.d(TAG, "intercept", newUrl.toString());

        return chain.proceed(newRequest);
    }
}
